import XLSX from 'xlsx'
import * as exportExcel from './exportExcel'

/**
 *读取excel文件
 * @param {File} file
 */
export function readExcelFile(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = function (e) {
      const data = e.target.result
      const workbook = XLSX.read(data, { type: 'binary' })
      resolve(workbook)
    }
    reader.readAsBinaryString(file)
  })
}
/**
 * 解析excel文件
 * @param {ParseProps} data
 * @interface ParseProps {
 *    file!: file
 *    sheetName!: string
 *    parseRowIdx!: ParseRowIdxItem[]
 *    minRow!: number
 * }
 * @interface ParseRowIdxItem {
 *    columnKey!: string
 *    label!: string
 * }
 */
export async function parseExcel(data) {
  try {
    const { file, sheetName, parseRowIdx, minRow } = data
    const fileData = await readExcelFile(file)
    const result = []
    const sheetNames = fileData.SheetNames
    const sheetData =
      fileData.Sheets[sheetName] || fileData.Sheets[sheetNames[0]]
    const maxRow = parseInt(
      sheetData['!ref'].split(':')[1].replace('IV', '')
    ) /** bug */
    for (let curRow = minRow; curRow <= maxRow; curRow++) {
      const item = {}
      parseRowIdx.forEach(({ columnKey, label }) => {
        const unitName = columnKey + curRow
        const unitData = sheetData[unitName] || {}
        item[label] = unitData.v || ''
      })
      item.id = curRow
      result.push(item)
    }
    return result
  } catch {
    return Promise.reject()
  }
}
/**
 * 解析excel文件
 * 参数同parseExcel
 */
export async function parseExcelToJson(data) {
  try {
    const { file, sheetName, parseRowIdx } = data
    const fileData = await readExcelFile(file)
    const sheetNames = fileData.SheetNames
    const sheetData =
      fileData.Sheets[sheetName] || fileData.Sheets[sheetNames[0]]
    const result = XLSX.utils.sheet_to_json(sheetData, {
      header: parseRowIdx.map((item) => item.label),
      raw: false,
    })
    result.splice(0, 2)
    result.map((item, i) => {
      item.id = i
      return item
    })
    return result
  } catch {
    return Promise.reject()
  }
}

// 导出excel文件
export function generateExcel(options) {
  return new Promise((resolve, reject) => {
    try {
      const baseOptions = {
        /**
         * @property {String[]} header
         * @property {String[]} data
         */
        // ...({ header, data })
        filename: 'excel',
        autoWidth: true,
        bookType: 'xlsx',
      }
      const _options = Object.assign({}, baseOptions, options)
      exportExcel.export_json_to_excel(_options)
      resolve()
    } catch (err) {
      console.log(err)
      reject()
    }
  })
}

/**
 *
 * @param {String} name
 */
export function getSuffixName(name) {
  return name.split('.').pop()
}

export function isExcel(file) {
  let name = ''
  return (
    file &&
    (name = file.name) &&
    typeof name === 'string' &&
    ['xlsx', 'xls'].includes(getSuffixName(name))
  )
}
